<template>
  <!-- 关联表格 -->
  <BouncedPanel class="table-container" @close="close" :showClose="false">
    <div class="title">
      {{ `事件列表(${transformEvent.name})` }}
    </div>
    <div class="table-content">
      <ScrollTable
        :tableLoading="tableLoading"
        scroll="calc(100% - .35rem)"
        rowKey="eventId"
        :columns="columns"
        :rowSelection="rowSelection"
        :dataSource="dataSource"
        :customRow="customRow"
      >
      </ScrollTable>
    </div>

    <!-- 底部操作取消 确认 -->
    <div class="btn-group">
      <a-button class="cancel" @click="close">取消</a-button>
      <a-button type="primary" class="confirm" @click="confirm" :disabled="rowSelection.selectKeys.length === 0">
        确认关联
      </a-button>
    </div>
  </BouncedPanel>
</template>
<script>
/** * @des: 关联表格 * @author: 刘清华 * @date: 2022/11/2 */

export default {
  name: 'IntelligentDetail'
}
</script>
<script setup>
import { reactive, ref, getCurrentInstance, onMounted, defineEmits, computed, defineProps } from 'vue'
import ScrollTable from '@/views/business-component/components/scroll-table'
import dayjs from 'dayjs'
import * as intelligentApi from '@/views/business-component/api/intelligent.js'
import { connectEvent } from '../../api/intelligent'
import { useStore } from 'vuex'

import BouncedPanel from '../../components/detail-panel'

const props = defineProps({
  detectionType: {
    type: [String, Number],
    default: ''
  },
  alarmType: {
    type: [String, Number],
    default: ''
  },
  transformEvent: {
    type: Object,
    default: () => {}
  }
})
const { proxy } = getCurrentInstance()
// 表头
const emit = defineEmits('close')
// 表格内容
const dataSource = ref([])
const store = useStore()
const intelligentData = computed(() => store.state.config.detailConfig.data)
const roadType = computed(() => store.state.config.roadType)
const $get = proxy.$get
const tableLoading = ref(false)

// 标题
const columns = [
  {
    title: '日期',
    dataIndex: 'eventStartTime',
    key: 'eventStartTime',
    width: '28%',
    ellipsis: true,
    customRender(record) {
      return record.text && dayjs(record.text).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  {
    title: '路段',
    dataIndex: 'roadNum',
    key: 'roadNum',
    width: '20%',
    ellipsis: true
  },
  {
    title: '桩号',
    dataIndex: 'pileStake',
    key: 'pileStake',
    ellipsis: true
  },
  {
    title: '调度员',
    dataIndex: 'createUsername',
    key: 'createUsername',
    width: 'auto'
  }
]

// table 单选参数
const rowSelection = reactive({
  hideSelectAll: true,
  columnWidth: 60,
  preserveSelectedRowKeys: false,
  type: 'radio',
  selectKeys: [],
  onChange(keys, record) {
    rowSelection.selectKeys = keys
  }
})

function customRow(record) {
  return {
    on: {
      click(record) {
        console.log(record)
      },
      dbclick(record) {
        console.log(record)
      }
    }
  }
}

onMounted(() => {
  getData()
})

/**
 * 请求list
 */
const getData = () => {
  tableLoading.value = true
  // TODO请求接口
  const params = {
    unitId: store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgId : null,
    eventType: props.transformEvent.eventType,
    roadSysType: roadType.value,
    companyType: $get(store.state, 'user.bussinessType'),
    page: 1,
    limit: 1000
  }
  intelligentApi
    .getAssociatedEventsList(params)
    .then(res => {
      if (res.data && res.data.data && res.data.data.length) {
        dataSource.value = res.data.data.map(item => {
          let roadNum = ''
          let pileStake = ''
          if (item.eventPositionList && item.eventPositionList.length) {
            // roadNum = eventRoadId + eventRoadName
            const eventRoadId = item.eventPositionList[0].eventRoadId || ''
            const eventRoadName = item.eventPositionList[0].eventRoadName || ''
            roadNum = eventRoadId

            const startStakeK = item.eventPositionList[0].eventStartMileageK
              ? 'K' + item.eventPositionList[0].eventStartMileageK
              : ''
            const startStakeM = item.eventPositionList[0].eventStartMileageM
              ? '+' + item.eventPositionList[0].eventStartMileageM
              : ''
            const endStakeK = item.eventEndMileageK ? '-K' + item.eventEndMileageK : ''
            const endStakeM = item.eventEndMileageM ? '+' + item.eventEndMileageM : ''
            pileStake = `${startStakeK} ${startStakeM} ${endStakeK} ${endStakeM}`
          }
          return {
            ...item,
            roadNum,
            pileStake
          }
        })
      } else {
        dataSource.value = []
      }
    })
    .finally(() => (tableLoading.value = false))
}

/**
 * 确认关联
 */
const confirm = () => {
  const params = {
    detectionId: intelligentData.value.detectionId, // 智能侦测Id
    unit: store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgId : null,
    detectionType: props.detectionType, //  智能侦测类型
    operator: store.state.user.userInfo.userId, // 操作人
    userName: store.state.user.userInfo.name,
    desc: '', // 智能侦测描述
    eventType: props.transformEvent.eventType, //  事件类型
    eventAttribute: '', // 突发性事件、计划类事件
    eventSource: intelligentData.value.eventSource, //  事件来源
    happenTime: intelligentData.value.monitorTime, //  发生时间
    endTime: '', //  结束时间
    roadSysType: roadType.value, //  事件环境变量 0公路 1高速
    assistantId: rowSelection.selectKeys[0], //  关联事件id
    ignoreType: 2, //  忽略误报状态 3:误报4:忽略   ... 1:确认事件;2:关联事件
    // ignoreDesc: '', //  忽略误报描述
    alarmType: props.alarmType, //  告警类型
    roadNum: intelligentData.value.roadNum, // 路线编号
    roadName: intelligentData.value.roadName, // 路线名称
    from: intelligentData.value.startStake, // 开始桩号
    to: intelligentData.value.endStake, // 结束桩号
    detectionSituationRequest: {
      districtId: '', // 省市区编码
      distance: intelligentData.value.jamDistance, // 拥堵距离
      duration: intelligentData.value.duration // 预计通行时间
    } //  列表项对象
    // 误报才有 desc
  }
  connectEvent(params)
    .then(res => {
      proxy.$message.success('关联成功')
      proxy.$bus.emit('overGetList', intelligentData.value.detectionId)
      emit('close')
    })
    .catch(e => {
      proxy.$message.success('关联失败')
    })
}

function close() {
  emit('close')
}
</script>
<style lang="less" scoped>
@import url('../../../../assets/styles/normalize/large-screen.less');
@import url('../../styles/themes/variables.less');

.table-container {
  display: flex;
  flex-direction: column;
  width: 570px;
  height: 516px;
  display: flex;
  border-radius: 20px;

  /deep/ .mz-panel-content > .title {
    display: none;
  }

  .title {
    width: 100%;
    height: 48px;
    line-height: 48px;
    font-family: 'pangmenzhengdaoregular';
    text-align: center;

    font-size: 16px;
  }

  .btn-group {
    width: 100%;
    height: 28px;
    line-height: 28px;
    overflow: hidden;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 9px;

    .cancel {
      width: 80px;
      height: 28px;
      background: #ffffff;
      border: 1px solid #999999;
      border-radius: 4px;
      color: #999999;
      padding: 0;
    }

    .confirm.ant-btn-primary {
      width: 80px;
      height: 28px;
      background: #ffffff;
      border: 1px solid #377ee9;
      color: #377ee9;
      border-radius: 4px;
      margin-left: 20px;
      padding: 0;
    }
  }

  .table-content {
    flex: 1;
    overflow: hidden;

    /deep/.ant-table-row:nth-child(even) {
      background-color: #f6f6f6;
    }

    /deep/.ant-table-row:nth-child(odd) {
      background-color: #e5eaf3;
    }

    /deep/.ant-table-row:hover {
      background-color: @row-hover-bg;
    }

    /deep/ .ant-table-row-selected > td {
      background-color: @row-active-bg !important;
    }

    /deep/ .ant-table-thead {
      .ant-table-cell {
        height: 32px;
        line-height: 32px;
        padding: 0;
      }
    }

    /deep/ .ant-table-tbody {
      .ant-table-cell {
        height: 36px;
        line-height: 36px;
        padding: 0;
      }
    }
  }
}
</style>
